import 'package:flutter/material.dart';
import 'package:hi_flutter/app_page.dart';

class InheritedWidgetDemoPage extends StatefulWidget {
  const InheritedWidgetDemoPage({super.key});

  @override
  State<InheritedWidgetDemoPage> createState() =>
      _InheritedWidgetDemoPageState();
}

class _InheritedWidgetDemoPageState extends State<InheritedWidgetDemoPage> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return AppPage(
      body: ShareDataWidget(
        data: count,
        child: Center(
          child: Column(
            children: [
              const TestWidget(),
              TextButton(
                  onPressed: () {
                    setState(() {
                      count = count + 1;
                    });
                  },
                  child: const Text('+1'))
            ],
          ),
        ),
      ),
    );
  }
}

class TestWidget extends StatefulWidget {
  const TestWidget({super.key});

  @override
  State<TestWidget> createState() => _TestWidgetState();

}

class _TestWidgetState extends State<TestWidget> {
  @override
  Widget build(BuildContext context) {
    print("build");
    return Text(ShareDataWidget.of(context)!.data.toString());
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("didChangeDependencies");
  }
}

class ShareDataWidget extends InheritedWidget {
  final int data; //需要在子树中共享的数据，保存点击次数

  const ShareDataWidget({
    Key? key,
    required this.data,
    required Widget child,
  }) : super(key: key, child: child);

  //定义一个便捷方法，方便子树中的widget获取共享数据
  // static ShareDataWidget? of(BuildContext context) {
  //   return context.dependOnInheritedWidgetOfExactType<ShareDataWidget>();
  // }

  //定义一个便捷方法，方便子树中的widget获取共享数据
  static ShareDataWidget? of(BuildContext context) {
    return context.getElementForInheritedWidgetOfExactType<ShareDataWidget>() !.widget as ShareDataWidget;
  }

  ////该回调决定当data发生变化时，是否通知子树中依赖data的Widget重新build
  @override
  bool updateShouldNotify(ShareDataWidget oldWidget) {
    return oldWidget.data != data;
  }
}
